<template>
  <div class="role-page">
    <section class="role-add">
      <h4>为角色添加用户</h4>
      <div class="role-list">
        <span v-for="item in options" :key="item.value">
          <el-button @click="addRoleName(item)"> {{item.label}} </el-button>
        </span>
      </div>
    </section>

    <section class="role-view">
      <h4>查看用户角色</h4>
      <div class="role-search">
        <el-row type="flex" justify="space-between">
          <el-form :model="roleForm">
            <el-col :span="5">
              <el-form-item label="角色" label-width="50px">
                <el-select v-model="roleForm.roleId" clearable placeholder="请选择角色">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="登录名" label-width="60px">
                <el-input v-model="roleForm.account"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="添加日期" label-width="80px">
                <el-date-picker
                 v-model="createTime"
                 type="daterange"
                 range-separator="至"
                 :picker-options="pickerOptions"
                 start-placeholder="开始日期"
                 end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="2" :offset="4">
              <el-form-item>
                <el-button type="primary" @click="searchList('roleForm')">查询</el-button>
              </el-form-item>
            </el-col>
          </el-form>
        </el-row>
      </div>

      <div class="role-table">
        <el-table :data="roleData" style="width: 100%" border stripe v-loading="loading">
          <el-table-column prop="roleName" label="角色名称">
          </el-table-column>
          <el-table-column prop="userName" label="用户名称">
          </el-table-column>
          <el-table-column prop="account" label="登录名">
          </el-table-column>
          <el-table-column prop="createTime" label="添加日期">
            <template slot-scope="scope">
              <span>{{fmtDate(scope.row.createTime)}}</span>
            </template>

          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageParam.currPage"
          :page-sizes="[20, 30, 50, 100]"
          :page-size="pageParam.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageParam.totalSize">
        </el-pagination>
      </div>
    </section>

    <!-- 添加用户 -->
    <el-dialog class="role-dialog" title="分配用户" :visible.sync="dialogFormVisible">
      <el-row :gutter="24">
        <el-form label-width="80px" :model="dialogForm">
          <el-col :span="10">
            <el-form-item label="角色名称">
              <el-input
                v-model="dialogForm.roleName"
                :disabled="true">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="登录名">
              <el-input
                v-model="dialogForm.account"
                :disabled="true">
              </el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>

      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>已分配用户</span>
        </div>
        <div class="already-tag">
          <el-tag
            v-for="tag in alreadyTags"
            closable
            :key="tag.id"
            :type="tag.type"
            @close="alreadyTagsRemove(tag)">
            {{tag.userName}}
          </el-tag>
        </div>
      </el-card>

      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>待分配用户</span>
        </div>
        <div class="await-tag">
          <el-tag
            v-for="tag in awaitTags"
            closable
            :key="tag.id"
            type="info"
            @close="awaitTagsAdd(tag)">
            {{tag.userName}}
          </el-tag>
        </div>
      </el-card>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUsers">确 定</el-button>
        <el-button @click="dialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

  import {roleQuery, getBindings, getUnBindings, bindUsers} from '@/server/userManagement'
  import {setStore, getStore} from '@/assets/js/common'

  export default {
    data: () => ({
      loading: false,
      alreadyTags: [],
      awaitTags: [],
      roleForm: {
        roleId: '',
        account: '',
        gt_createTime: '',
        lt_createTime: '',
        currPage: 0,
        pageSize: 30
      },
      pageParam:{
        currPage: 1,//默认当前页数
        pageSize: 30,//默认当前页大小
        totalSize: 0,//总数据条数
      },
      createTime: null,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e6
        }
      },
      options: [{
        value: '1',
        label: '业务员'
      }, {
        value: '2',
        label: '业务领导'
      }, {
        value: '3',
        label: '单证员'
      }, {
        value: '4',
        label: '单证领导'
      }, {
        value: '5',
        label: '风控员'
      }, {
        value: '6',
        label: '财务'
      }, {
        value: '7',
        label: '管理员'
      }],
      //roleDataT: this.roleDatas,
      roleData: [],
      roleId: '',
      dialogFormVisible: false,
      dialogForm: {
        roleName: '',
        account: ''
      },
      submitUsersObj: {
        roleId: '',
        roleName: '',
        userIds: ''
      },
      userIdArr: []
    }),
    // props: ['roleDatas'],
    // computed: {
    //   createTime: function () {
    //     return this.fmtDate(createTime)
    //   }
    // },
    created() {
      this.initPage();
      this.roleQueryFn();
      // this.searchList();
    },
    methods: {
      initPage() {
        this.roleForm.currPage = 0;
        this.roleForm.pageSize = 30;
      },
      roleQueryFn(paramObj) {
        this.loading = true;
        roleQuery(paramObj).then((res) => {
          try {
            if (res.code == '1') {
             let sData = res.data.datas;
             this.roleData = sData;
             this.pageParam.pageSize = res.data.pageSize;
             this.pageParam.currPage = res.data.currPage + 1;
             this.pageParam.totalSize = res.data.totalSize;
            } else {
             this.$message.error(res.message);
            }
          } catch (e) {
             this.$message.error('查询请求异常');
          }
          this.loading = false;

        })
      },
      fmtDate(obj) {
          var date =  new Date(obj);
          var y = 1900 + date.getYear();
          var m = "0" + (date.getMonth()+1);
          var d = "0" + date.getDate();
          return y + "/" + m.substring(m.length - 2, m.length) + "/" + d.substring(d.length - 2 ,d.length);
      },
      searchList () {

        try {
          let sT = this.createTime[0].getTime();
          let eT = this.createTime[1].getTime() + (24 * 3600 * 1000);
          this.roleForm.gt_createTime = sT;
          this.roleForm.lt_createTime = eT;
        } catch (e) {
          delete this.roleForm.gt_createTime;
          delete this.roleForm.lt_createTime;
        }

        if (!this.roleForm.roleId) delete this.roleForm.roleId;
        if (!this.roleForm.account) delete this.roleForm.account;

        this.initPage();
        this.roleQueryFn(this.roleForm);

      },
      handleSizeChange(val) {
        this.roleForm.currPage = 0;
        this.roleForm.pageSize = `${val}`;
        this.roleQueryFn(this.roleForm);
      },
      handleCurrentChange(val) {
        this.roleForm.currPage = `${val}` - 1;
        this.roleQueryFn(this.roleForm);
      },
      getBindingsFn(paramObj) {
        getBindings(paramObj).then((res) => {
          try {
            if (res.code) {
             let sData = res.data.datas;
             this.alreadyTags = sData[0];
            } else {
             this.$message.error(res.message);
            }
          } catch (e) {
             this.$message.error('服务器请求异常');
          }
        })
      },
      getUnBindingsFn(paramObj) {
        getUnBindings(paramObj).then((res) => {
          try {
            if (res.code == '1') {
             let sData = res.data.datas;
             this.awaitTags = sData[0];
            } else {
             this.$message.error(res.message);
            }
          } catch (e) {
             this.$message.error('服务器请求异常');
          }

        })
      },
      addRoleName (val) {

        this.userIdArr = [];

        let userMsgObj = JSON.parse(getStore('userMsg'));

        this.dialogFormVisible = true;

        this.dialogForm.roleName = val.label;
        this.dialogForm.account = userMsgObj.account;

        this.submitUsersObj.roleId = val.value;
        this.submitUsersObj.roleName = val.label;


        let roleObj = {
          roleId: val.value
        }

        this.getBindingsFn(roleObj);
        this.getUnBindingsFn(roleObj);

      },
      submitUsers() {
        this.userIdArr = [];
        for (let list of this.alreadyTags) {
          this.userIdArr.push(list.id)
        }

        this.submitUsersObj.userIds = this.userIdArr.toString();

        bindUsers(this.submitUsersObj).then((res) => {
          try {
            if (res.code) {

              this.$message({
                showClose: true,
                message: res.message,
                type: 'success'
              });
              this.searchList();

            } else {
             this.$message.error(res.message);
            }
          } catch (e) {
             this.$message.error('分配用户失败');
          }
          this.dialogFormVisible = false;

        })
      },
      handleInputConfirm() {
        let inputValue = this.inputValue;
        if (inputValue) {
          this.dynamicTags.push(inputValue);
        }
        this.inputVisible = false;
        this.inputValue = '';
      },
      alreadyTagsRemove(tag) {
        this.alreadyTags.splice(this.alreadyTags.indexOf(tag), 1);

        Array.prototype.removeByValue = function(val) {
          for(var i=0; i<this.length; i++) {
            if(this[i] == val) {
              this.splice(i, 1);
              break;
            }
          }
        }

        if (tag) {
          this.awaitTags.push(tag);
          this.userIdArr.removeByValue(tag.id);
        }
      },
      //待分配用户
      awaitTagsAdd(tag) {
        this.awaitTags.splice(this.awaitTags.indexOf(tag), 1);

        // let inputValue = this.inputValue;
        // console.log(tag,'----tag');

        if (tag) {
          this.alreadyTags.push(tag);
          // console.log(tag,'---tag');

          this.userIdArr.push(tag.id);

        }
      }
    }
  }
</script>

<style lang="sass">
  @import "../../../assets/css/common.sass"

  .role-page
    section
      margin-bottom: 50px
      // display: block
      h4
        margin-bottom: 20px
        font-size: 16px
        background: #e6e6e6
        line-height: 40px
        padding: 0 10px
      .role-list
        >span
          margin-right: 20px
  .role-search
    width: 100%
    border: 1px solid #e6ebf5
    border-radius: 4px
    padding: 20px
    padding-bottom: 10px
    box-sizing: border-box
    &:after
      @include clear
    .el-col
      >span~div
        display: inline-block
  .role-table
    box-sizing: border-box
    border-radius: 4px
    margin-top: 20px
    border-right: none
    .el-table
      border-radius: 4px
  .el-form-item
    margin-bottom: 20px
    .el-input, .el-textarea, .upload-demo
      width: 95%
  .role-dialog
    .el-dialog__body
      padding: 0 20px
    .el-card
      margin: 10px auto
      .el-card__body
        padding: 10px
        .already-tag, .await-tag
          span
            margin: 10px
            position: relative
        .await-tag
          .el-tag__close
            width: 100%
            position: absolute
            left: 0
            height: 100%
            opacity: 0

</style>
